<template>
  <div class="main">
    <Header :showAimeTip="showAimeTip" @showAime="showAime" @hiddenAimeTip="showAimeTip = false" />
    <div class="block">
      <div class="content-container">
        <div class="content">
          <CusFilter
            :showType="showType"
            :tabValue="tabValue"
            :radioValue="radioValue"
            :isShowTurnover="isShowTurnover"
            @update:tabValue="updateTabValue"
            @update:radioValue="updateRadioValue"
            @update:isShowTurnover="updateShowTurnover"
          />
          <keep-alive>
            <div
              class="table-container"
              v-clickOutside="initActiveBlock"
              v-if="showType === 'home'"
            >
              <Table
                v-for="(columns, index) in columnsArr"
                :key="index"
                :hasGuide="index === 0"
                :activeBlockCode="activeBlockCode"
                :activeInfo="activeInfoArr[index]"
                :isShowTurnover="isShowTurnover"
                :title="`${titleArr[index]}期趋势`"
                :columns="columns"
                :loading="homeLoading"
                :tableData="tableDataArr[index]"
                :titleTipsContent="config.tipsArr[index].titleTips"
                @lookmore="setShowType('history', index)"
                @updateActiveBlock="updateActiveBlock"
              />
            </div>
          </keep-alive>
          <History
            v-if="showType === 'history'"
            :historyIndex="historyIndex"
            :title="`${titleArr[historyIndex]}期趋势历史`"
            :blockType="tabValue"
            @setSelection="setSelection"
            @goback="setShowType('home')"
          />
        </div>
      </div>
      <PcAime
        :value="isShowAime"
        app_id="6705e942e4b08f184e4da18f"
        title="板块趋势雷达"
        greeting="你好，我是板块分析助手。我可以帮您分析研判板块趋势，更快更全面地了解板块"
        :recommendContents="[]"
        placeholder="请输入内容"
        :primarySelection="activeSelection"
        :primarySelectionData="activeSelectionData"
        @update="hideAime"
        @clearPrimarySelection="clearPrimarySelection"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { CusFilter, Table, History } from '_c/Home/index.ts';
import { reqDetail } from '_a';
import { errorReport } from '_t';
import { useHomeData, useActiveBlock, useFilter, useTimingUpdate, useAime } from '@/hooks/index.ts';
import { BlockType } from '@/types/api';
import { HistoryIndex } from '@/types/history';
import { radioNum, type ShowType } from '@/types/filter';
import config from '@/config/index.ts';
import { ActiveTable } from '@/types/table';

const instance = getCurrentInstance() as any;
// 获取当前缓存实例
const localforageIns = instance.proxy.$localforageIns;
/**
 * 设置选中板块逻辑
 * activeBlockCode - 当前选中的板块code
 * rankArr - 当前三个表格的排名
 * initActiveBlock - 初始化选中板块
 * setActiveBlock - 设置选中板块
 */
const {
  activeBlockCode,
  activeBlockMarketId,
  activeSelection,
  activeSelectionData,
  activeInfoArr,
  initActiveBlock,
  setActiveBlock,
  setSelection,
  clearPrimarySelection
} = useActiveBlock();
const updateActiveBlock = ({ code, name, market, title }: ActiveTable) => {
  setActiveBlock({ code, name, market, title });
  // 点击的时候需要更新一下表格数据，防止调用的排名和表格显示的不同
  getHomeData();
  getDetail();
};

// 获取股票详情内容
const getDetail = () => {
  const apiParams = {
    code: activeBlockCode.value,
    market: activeBlockMarketId.value,
    date: date.value
  };
  reqDetail(apiParams)
    .then(
      ({
        rise_range_rank,
        rise_range_rank_change,
        g_percent_rank,
        g_percent_rank_change,
        n_percent_rank,
        n_percent_rank_change
      }) => {
        activeInfoArr.value = [
          { rank: rise_range_rank, rankChange: rise_range_rank_change },
          { rank: g_percent_rank, rankChange: g_percent_rank_change },
          { rank: n_percent_rank, rankChange: n_percent_rank_change }
        ];
      }
    )
    .catch(error => {
      errorReport({
        name: `首页获取数据详情失败。${error.name}`,
        message: `入参为${JSON.stringify(apiParams)}。error.message为${error.message}`,
        stack: error.stack
      });
    });
};
/**
 * 过滤逻辑
 * tabValue - 全部，行业，概念
 * radioValue - 上榜标红展示
 * isShowTurnover - 是否显示成交额
 * setTabValue - 设置过滤
 * setRadioValue - 设置是否显示成交额
 * setShowTurnover - 设置是否显示成交额
 */
const { tabValue, radioValue, isShowTurnover, setTabValue, setRadioValue, setShowTurnover } =
  useFilter();

const updateTabValue = (value: BlockType) => {
  const statOptions = {
    // 空值主要是给接口入参使用，这里要做一个映射给埋点使用
    '': 'all',
    cn_industry: 'industry',
    cn_concept: 'concept'
  };
  window.TA.log({ id: `${config.statHomePage}.stockclass_${statOptions[value]}.click` });
  setTabValue(value);
  getHomeData();
};
const updateRadioValue = (value: string) => {
  const { short, medium, long } = radioNum;
  const statOptions: Record<string, string> = {
    [`${short},${medium},${long}`]: 'shortmediumlong',
    [`${short},${medium}`]: 'shortmedium',
    [`${short},${long}`]: 'shortlong'
  };
  window.TA.log({ id: `${config.statHomePage}.rankclass_${statOptions[value]}.click` });
  setRadioValue(value);
  getHomeData(true);
};
const updateShowTurnover = (value: boolean) => {
  setShowTurnover(value);
  getHomeData();
};

/**
 * 获取数据逻辑
 * date - 接口返回日期
 * tableDataArr - 表格数据
 * columnsArr - 表头列
 * titleArr - 表格标题
 * getHomeData - 获取数据
 */
const { date, tableDataArr, columnsArr, titleArr, getHomeData, homeLoading } = useHomeData(
  radioValue,
  tabValue
);
const showType = ref<ShowType>('home');
const historyIndex = ref<HistoryIndex>(0);
const setShowType = (cusShowType: ShowType, index?: HistoryIndex) => {
  showType.value = cusShowType;
  if (index !== void 0) {
    historyIndex.value = index;
  }
};

// 定时更新数据
useTimingUpdate(() => {
  if (showType.value !== 'home') {
    return;
  }
  // 获取数据之后更新排名数据
  getHomeData();
  activeBlockCode.value && getDetail();
});

// Aime
const { isShowAime, showAime, hideAime, showAimeTip } = useAime(localforageIns);

onMounted(() => {
  getHomeData();
  window.TA.log({ id: `${config.statHomePage}` });
});
</script>

<style scoped lang="less">
.main {
  margin: 6px 8px;
  display: flex;
  flex-direction: column;
  .block {
    display: flex;
    height: calc(100vh - 50px);
    .content-container {
      width: 100%;
      overflow-x: scroll;
      overflow-y: hidden;
      background: #161616;
      .content {
        width: 100%;
        min-width: 974px;
        max-width: 1446px;
        background: #161616;
        border-radius: 4px;
        padding: 8px;
        margin: 0 auto;
      }
    }
    .table-container {
      margin-top: 6px;
      display: flex;
      justify-content: center;
      height: calc(100vh - 100px);
      > * {
        margin-right: 7px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}
</style>
